package com.glsc.ngateway.platform.controller.it;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.PageConstant;
import com.glsc.ngateway.common.api.platform.dto.it.NetworkManageExportFull;
import com.glsc.ngateway.common.api.platform.dto.it.ParamSearchNetworkDto;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItNetworkDevice;
import com.glsc.ngateway.common.base.utils.NGSMDateTimeFormatter;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.it.NetworkService;
import com.glsc.ngateway.platform.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.ROLE_OPEARATOR;

@Deprecated
@RestController
@RequestMapping("/it/network")
@Api(value = "网络管理", tags = {"网络管理"})
public class NetworkManageController {

    private static final Logger logger = LoggerFactory.getLogger(NetworkManageController.class);

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserCache userCache;
    @Autowired
    private NetworkService networkService;
    @Autowired
    private UserService userService;

    @Value("${export.it}")
    public String itpath;

    //查询设备
//    @RequestMapping(method = RequestMethod.GET, value = "query")
//    @ApiOperation(value = "查询设备", notes = "查询设备")
//    public PlatformResponseNew querySerList(
//            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
//            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
//
//        if (pageNo == null) {
//            pageNo = 1;
//        }
//        if (pageSize == null) {
//            pageSize = PageConstant.PageSize;
//        }
//
//        PlatformUserDto user = userCache.get(request);
//        String userid = user.getUserid();
//        if ("admin".equals(user.getUsername())) {
//            userid = null;
//        }
//        Page<ItNetworkDevice> result = networkService.queryAllSer(pageNo, pageSize, userid);
//        PlatformResponseNew ret = PlatformResponseNew.success();
//        ret.setData(result);
//        return ret;
//    }


    /*
     * 提交或修改项目
     */
    @RequestMapping(method = RequestMethod.POST, value = "addOrUpdate")
    @ApiOperation(value = "提交或修改项目", notes = "提交或修改项目")
    public PlatformResponse<Void> addOrUpdateNetwork(@RequestBody ItNetworkDevice itNetworkDevice) throws ParseException {

//        if (StringUtils.isEmpty(itNetworkDevice.getAssetId())) {
//            return PlatformResponseNew.failedMsg("addOrUpdateNetwork接口，id为空。");
//        }
        //日期转换

        if (!StringUtils.isEmpty(itNetworkDevice.getStartTimeStr())) {
            Instant instant = NGSMDateTimeFormatter.sdf.parse(itNetworkDevice.getStartTimeStr()).toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            itNetworkDevice.setStartTime(localDateTime);
        }
        if (!StringUtils.isEmpty(itNetworkDevice.getEndTimeStr())) {
            Instant instant = NGSMDateTimeFormatter.sdf.parse(itNetworkDevice.getEndTimeStr()).toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            itNetworkDevice.setEndTime(localDateTime);
        }

        PlatformUserDto user = userCache.get(request);
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if (!"itadmin".equals(user.getUsername()) && !roleNames.contains(ROLE_OPEARATOR) && !roleNames.contains("IT_ASSET_NET_DEVICE_DATA_AUTH")) {
            return PlatformResponse.failedMsg("addOrUpdateNetwork接口，没有该功能权限。");
        }
        networkService.addOrUpdateNetwork(itNetworkDevice, user.getUserid());
        return PlatformResponse.successMsg("创建或修改成功");
    }

    /*
     * 删除设备
     */
    @RequestMapping(method = RequestMethod.POST, value = "delete")
    @ApiOperation(value = "删除设备", notes = "删除设备")
    public PlatformResponse<Void> deleteNetwork(@RequestBody String assetId) {
        if (StringUtils.isEmpty(assetId)) {
            return PlatformResponse.failedMsg("deleteNetwork接口，id为空。");
        }
        PlatformUserDto user = userCache.get(request);
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if (!"itadmin".equals(user.getUsername()) && !roleNames.contains(ROLE_OPEARATOR) && !roleNames.contains("IT_ASSET_NET_DEVICE_DATA_AUTH")) {
            return PlatformResponse.failedMsg("deleteNetwork接口，没有该功能权限。");
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(assetId);
        String id = jsonObject.getString("assetId");
        if (StringUtils.isNotEmpty(id)) {
            networkService.deleteNetwork(id);
        }
        return PlatformResponse.successMsg("删除设备成功");
    }


        //搜索网络设备
    @RequestMapping(value = "/searchNetwork", method = {RequestMethod.GET, RequestMethod.POST})
    public Object searchNetwork(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String nw = (String) request.getParameter("nw");
        String isLikeString = request.getParameter("isLike");
        List<ItNetworkDevice> result = new ArrayList<>();
        if (StringUtils.isNotEmpty(isLikeString) && isLikeString.equals("true")){
            result = networkService.searchNetworkSpecial(nw,true);
        } else {
            result = networkService.searchNetworkSpecial(nw,false);
        }
        return result;
    }
//
//
//    //搜索网络设备名称
//    @RequestMapping(value = "/multiSearch", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object multiSearchNetwork(com.jlwang.rest.asset.boundary.NetworkManageAddOrUpdateInput input,
//                                     HttpServletRequest request, HttpServletResponse response) throws Exception {
//        /*验证新增权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得该权限，请联系管理员");
//        /*验证新增权限end*/
//        Map<String, Object> networkInfo = BeanUtil.bean2Map(input);
//
//        List<Map<String, Object>> result = networkService.multiSearch(networkInfo);
//
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.saveResultSet(result);        //保存搜索数据
//        return jsonResult;
//    }
    //    //搜索网络设备
    @RequestMapping(method = RequestMethod.POST, value = "search")
    @ApiOperation(value = "搜索网络设备", notes = "搜索网络设备")
    public PlatformResponse<Page<ItNetworkDevice>> searchNetwork(@RequestBody ParamSearchNetworkDto params) {
        if (params.getPageNo() == null) {
            params.setPageNo(PageConstant.PageNo);
        }
        if (params.getPageSize() == null) {
            params.setPageSize(PageConstant.PageSize);
        }
        PlatformUserDto user = userCache.get(request);
        String userId = user.getUserid();
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if ("itadmin".equals(user.getUsername()) || roleNames.contains(ROLE_OPEARATOR) || roleNames.contains("IT_ASSET_NET_DEVICE_DATA_AUTH")) {
            userId = null;
        }
        String assetIp = params.getAssetIp();
        String brandType = params.getBrandType();
        String brandSys = params.getBrandSys();
        String brandSn = params.getBrandSn();
        String capitalTyped = params.getCapitalTyped();
        String brand = params.getBrand();
        String capitalType = params.getCapitalType();
        if (StringUtils.isEmpty(params.getAssetIp())) {
            assetIp = null;
        }
        if (StringUtils.isEmpty(params.getBrandType())) {
            brandType = null;
        }
        if (StringUtils.isEmpty(params.getBrandSys())) {
            brandSys = null;
        }
        if (StringUtils.isEmpty(params.getBrandSn())) {
            brandSn = null;
        }
        if (StringUtils.isEmpty(params.getCapitalTyped())) {
            capitalTyped = null;
        }
        if (Strings.isBlank(params.getBrand())) {
            brand = null;
        }
        if (StringUtils.isEmpty(params.getCapitalType())) {
            capitalType = null;
        }
        Page<ItNetworkDevice> result = networkService.searchNetwork(params.getPageNo(), params.getPageSize(), userId, assetIp, brandType, brandSys, brandSn, capitalTyped, brand, capitalType);
        return PlatformResponse.successData(result);
    }

    //    // 查询资产标牌清单
//    @RequestMapping(value = "/queryTypeIdList", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object queryTypeIdList(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String typeId = (String) request.getParameter("typeId");
//        List<Map<String, Object>> result = networkService.queryTypeByTypeId(typeId);
//
//        // 整理输出信息
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.saveResultSet(result);
//        return jsonResult;
//    }
//
    //导出excel
    @RequestMapping(method = RequestMethod.POST, value = "export")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public ResponseEntity<byte[]> exportNetworkFullOutPut() throws IOException {
        /*验证新增权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得导出权限，请联系管理员");
        /*验证新增权限end*/
        List<NetworkManageExportFull> result = networkService.queryNetworkFullOutPut();
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "网络设备").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "wlsb.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }
//
//
//
//    /*
//     * 多设备删除
//     */
//    @RequestMapping(value = "/deleteMultNetwork", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object deleteMultNetwork(String[] ids, HttpServletRequest request, HttpServletResponse response)
//            throws Exception {
//        /*验证删除权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限删除
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "没有删除权限");
//        /*验证删除权限end*/
//        Objects.requireNonNull(ids);
////		String userId = (String) request.getAttribute("currentUserId");
////		if (!projectService.isValidProjectMember(projectId, userId))
////			throw new BizException("对不起，您没有本项目的操作权限。");
//
//        networkService.deleteMultNetwork(ids);
//        // 整理输出信息
//        JsonResult jsonResult = new JsonResult();
//        return jsonResult;
//    }
}